package com.example.backend.repository;

import com.example.backend.domain.entity.Comment;
import com.example.backend.domain.enums.CommentType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
    
    List<Comment> findByTicketIdOrderByCreatedAtAsc(Long ticketId);
    
    Page<Comment> findByTicketIdOrderByCreatedAtDesc(Long ticketId, Pageable pageable);
    
    List<Comment> findByTicketIdAndCommentTypeOrderByCreatedAtAsc(Long ticketId, CommentType commentType);
    
    List<Comment> findByTicketIdAndIsInternalFalseOrderByCreatedAtAsc(Long ticketId);
    
    List<Comment> findByTicketIdAndIsInternalTrueOrderByCreatedAtAsc(Long ticketId);
    
    List<Comment> findByParentIdOrderByCreatedAtAsc(Long parentId);
    
    @Query("SELECT c FROM Comment c WHERE c.ticket.id = :ticketId AND c.parent IS NULL ORDER BY c.createdAt ASC")
    List<Comment> findTopLevelCommentsByTicketId(@Param("ticketId") Long ticketId);
    
    @Query("SELECT c FROM Comment c WHERE c.author.id = :authorId ORDER BY c.createdAt DESC")
    Page<Comment> findByAuthorId(@Param("authorId") Long authorId, Pageable pageable);
    
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.ticket.id = :ticketId")
    Long countByTicketId(@Param("ticketId") Long ticketId);
    
    @Query("SELECT COUNT(c) FROM Comment c WHERE c.ticket.id = :ticketId AND c.isInternal = :isInternal")
    Long countByTicketIdAndIsInternal(@Param("ticketId") Long ticketId, @Param("isInternal") Boolean isInternal);
}